/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var marque_ref        = {};//marque+prix_ref
var price_coef      = {};//coeficient des prix en fonction de type de vetement
var allmarques      = [];//les marques seules
var allvetements    = [];//les types de vetements: jeans,...
var vet_selected    = '';
var marq_selected   = '';
var price_ref       = 0;//le prix de reference 
var coef_min        = 0;//le coef mini
var coef_max        = 0;

function init_estimation(){//initialise les inputs!
   
  jQuery( document ).ready( function(){
       getMarques_ref();
       getPrices_ref();
       //erase_inputs();
       marque_acceptee();
  });
    
}
function getMarques_ref(){//récupère tous les prix des articles!
    
    jQuery.ajax({
        type:'post',
        url:'index.php?option=com_cashestimation&view=estimationslist&task=list_marque&format=raw',
        dataType: 'JSON'
    }).done(function(d){
     manage_marque(d);
     autocomplete_marque();
    });
}

function getPrices_ref(){
    
     jQuery.ajax({
        type:'post',
        url:'index.php?option=com_cashestimation&view=estimationslist&task=list_price&format=raw',
        dataType: 'JSON'
    }).done(function(d){
       manage_price(d);
       options_vetement_event();
       //autocomplete_vetement();
    });
}
function manage_marque(data){//associe une marque+un type= prix!
    
    jQuery.each(data, function(idx,ele){
        var i = ele['marque_produit'];
        i=i.toUpperCase();
      marque_ref[i]= ele['prix_ref'];
      allmarques.push(i);
    });
}

function manage_price(data){
    
    jQuery.each(data, function(idx,ele){
        var i = ele['type'].toUpperCase();
      price_coef[i]= ele['coef_min']+'|'+ele['coef_max'];
      allvetements.push(i);
    });
}
function init_constances(){
    
vet_selected    = '';
marq_selected   = '';
price_ref       = 0;//le prix de reference 
coef_min        = 0;//le coef mini
coef_max        = 0;
}

function autocomplete_marque(){
    
    var html    = [];
    html.push('<option></option>');
    jQuery.each(allmarques, function (i,e){
        html.push('<option value="'+e+'">'+e+'</option>');
    });
    
    jQuery("#trade_choices").html(html.join(''));
}
function autocomplete_marque(){//selection d'une marque
    
    jQuery(".estimator_input").children("input[type='text']").eq(0).autocomplete({
        source: allmarques,
        select:function( event, ui ) {
			marq_selected=ui.item.label;
			price_ref   = parseFloat(marque_ref[marq_selected]);
                       // vet_selected = jQuery("#input_type_vet").val();
                       // console.log(vet_selected);
                        //if(vet_selected !== ''){
                            var min = price_ref*coef_min;
                            var max = price_ref*coef_max;
                         
                            animateValue(jQuery("#just_price_1"), 0, min, 100); //min
                            animateValue(jQuery("#just_price_2"), 0, max, 100); //min
                        //}
		}
    });
}


    
   
/*function autocomplete_vetement(){//selection d'un type de vetement: jeans, jupe,...
    
    jQuery(".estimator_input").children("input[type='text']").eq(0).autocomplete({
        source: allvetements,
        select:function( event, ui ) {
            
			vet_selected=ui.item.label;
                        getCoefs(price_coef[vet_selected]);
                        
                        if(marq_selected !== ''){
                            var min = price_ref*coef_min;
                            var max = price_ref*coef_max;
                           animateValue(jQuery("#just_price_1"), 0, min, 100); //min
                            animateValue(jQuery("#just_price_2"), 0, max, 100); //min
                           
                        }
		}
    });
}*/
function options_vetement(){
    
    var html= [];
    jQuery.each(allvetements, function(){
       
        html.push('<option>'+this+'</option>');
    });
    vet_selected    = allvetements[0];
    getCoefs(price_coef[vet_selected]);
    jQuery("#input_type_vet").html(html.join(''));
}
function options_vetement_event(){
    options_vetement();
    
    jQuery("#input_type_vet").change(function(){
        
        vet_selected=jQuery(this).val();
        
        getCoefs(price_coef[vet_selected]);
                        
        if(marq_selected !== ''){
           var min = price_ref*coef_min;
           var max = price_ref*coef_max;
           animateValue(jQuery("#just_price_1"), 0, min, 100); //min
               animateValue(jQuery("#just_price_2"), 0, max, 100); //min
                           
            }
        
    });
    
}


function getCoefs(coefs){
    
    var t= coefs.split("|");
    coef_max    = parseFloat(t[1]);
    coef_min    = parseFloat(t[0]);
}


function animateValue(id, start, end, duration) {
    var range = end - start;
    var current = start;
    var increment = 0.1;//end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    //var obj = document.getElementById(id);
    var timer = setInterval(function() {
        current += increment;
        id.html(current.toFixed(0)+'.00');// = ;//obj
        if (current - end > 0) {
            clearInterval(timer);
        }
    }, stepTime);
}

function marque_acceptee(){
    
    jQuery("#saisir_marque").bind('keyup',function(){
     
        var v= jQuery(this).val();
        if(typeof v=== 'undefined' || v===''){
            jQuery("#display_response").html('');
        }else{
            var m= v.toUpperCase();

           if(jQuery.inArray( m, allmarques) > -1){

               jQuery("#display_response").html('<img src="../templates/cashdressing/images/checkmark_yes.png" >&nbsp;&nbsp;Nous acceptons cette marque');
           }
           else{
               jQuery("#display_response").html('<img src="../templates/cashdressing/images/checkmark_no.png" >&nbsp;&nbsp; Malheureusement nous n\'acceptons pas cette marque');
           }
      }
    });
}
function getMarques_marques(){//récupère tous les prix des articles!
    
    jQuery.ajax({
        type:'post',
        url:'index.php?option=com_cashestimation&view=estimationslist&task=list_marque&format=raw',
        dataType: 'JSON'
    }).done(function(d){
        manage_marque(d);
     display_marques();
     auto_marque();
    });
}
function repartir_marques(){//repartition alphabtique
    var obj={};
    
    jQuery.each(allmarques, function(i,e){
        var f= e.charAt(0);
        var tmp=[];
        if(isNaN(f)){
         if(typeof obj[f] !== 'undefined')  tmp= obj[f];
            tmp.push(e);
            obj[f]=tmp;
        }else{
            if(typeof obj[f] !== 'undefined') tmp   = obj[f];
            tmp.push(e);
            obj['1,2...9']=tmp;
        }
    });
    return obj;
}

function launche_marques(){
    
    getMarques_marques();
}
function display_marques(){
    
    var o = repartir_marques();
   
    jQuery("#display_marques_tbl").html('');
    jQuery.each(o,function(i,e){
      jQuery("#display_marques_tbl").append(display_table(i,e)+'<br>');  
        
    });
}

function display_table(letter, table){
    var html=[];
    var l= table.length;
    html.push('<table width="100%" class="table_cash"><tr><th colspan="8" class="tbl_marques">'+letter+'</th>');
    if( l>4){
        jQuery.each(table, function(i,e){

            if(i%4 === 0)
                html.push('</tr><tr><td>'+e+'</td>');
            else{

                html.push('<td>'+e+'</td>');
            }           
        });
    }
    else{
        html.push('</tr><tr>');
        for(var j=0;j<l;j++)
            html.push('<td>'+table[j]+'</td>');
    }
    html.push('</tr></table>');
    
    return html.join('');
}

function auto_marque(){//selection d'une marque
    
    jQuery(".chercher_marque").children("input[type='text']").autocomplete({
        source: allmarques,
        select:function( event, ui ) {
			var v= ui.item.label;
                if(typeof v=== 'undefined' || v===''){
                    jQuery("#display_response").html('');
                }else{
                    var m= v.toUpperCase();

                   if(jQuery.inArray( m, allmarques) > -1){

                       jQuery("#display_response").html('<img src="../templates/cashdressing/images/checkmark_yes.png" >&nbsp;&nbsp;Nous acceptons cette marque');
                   }
                   else{
                       jQuery("#display_response").html('<img src="../templates/cashdressing/images/checkmark_no.png" >&nbsp;&nbsp; Malheureusement nous n\'acceptons pas cette marque');
                   }
              }
         }
    });
}